import { useRef } from "react";
import { Tag } from "antd";
import { isHexColor } from "@/utils/color";
import type { DictDataType } from "@/utils/dict";
import { getDictDatas } from "@/utils/dict";

interface PropType {
	type: string;
	value?: string | number | boolean;
	icon?: { type: string };
}

const dictTag = (props: PropType) => {
	const dictData = useRef<DictDataType>();
	const getDictObj = (dictType: string, value: string) => {
		let dictOptions: DictDataType[] = [];
		dictOptions = getDictDatas(dictType);
		if (dictOptions && dictOptions.length === 0) return;

		dictOptions.forEach((dict: DictDataType) => {
			if (dict.value === value) {
				if (`${dict.colorType}` === "primary") dict.colorType = "processing";
				else if (`${dict.colorType}` === "danger") dict.colorType = "error";
				else if (`${dict.colorType}` === "info") dict.colorType = "default";

				dictData.current = dict;
			}
		});
	};
	if (!props.type) return null;

	// 解决自定义字典标签值为零时标签不渲染的问题
	if (props.value === undefined || props.value === null) return null;
	getDictObj(props.type, props.value.toString());
	if (dictData.current === undefined) return null;

	// 添加标签的文字颜色为白色，解决自定义背景颜色时标签文字看不清的问题 && isHexColor(dictData.value?.cssClass)
	return (
		<Tag
			color={
				dictData.current?.colorType
					? dictData.current?.colorType
					: dictData.current?.cssClass && isHexColor(dictData.current?.cssClass)
					? dictData.current?.cssClass
					: ""
			}
		>
			{dictData.current?.label || ""}
		</Tag>
	);
};

export default dictTag;
